<?php

namespace App\Services\Account;

use App\Models\Account\UserAccountModel;
use App\Models\Account\UserEmailModel;
use App\Models\UserModel;
use App\Services\BaseService;
use App\Services\Common\CommonService;
use App\Services\Common\RedisService;

class UserEmailService extends BaseService
{

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new UserEmailModel();
    }

    /**
     * @Notes:获取用户与账号管理信息
     * @Interface getList
     * @return array
     * @author: wuyu
     * @Time: 2023/6/2   19:10
     */
    public function getList()
    {
        $param = request()->all();
        // 查询条件
        $map[] = ['mark','=',1];
        $user = getter($param, 'user', 0);
        $account = getter($param, 'account', '');
        $sort = getter($param, 'sort', 'id');
        $order = getter($param, 'order', 'desc');

        if (!empty($user)) $map[] = ['user_id', '=', $user];
        if (!empty($account)) $map[] = ['account_name', '=', $account];

        //权限过滤
        $createUserList = CommonService::userAuth();

        $model2 = $this->model->where($map);
        if (!empty($createUserList)) $model2->whereIn('user_id',$createUserList);
        $count = $model2->count();
        if (!empty($createUserList)) $map[] = ['user_id', 'in', $createUserList];
        $list = $this->model->getList($map, [[$sort, $order]]);
        foreach ($list as $key => $val) {
            $val['email_pass_new'] = $this->replaceStr($val['email_pass']);
            $list[$key] = $val;
        }
        return array(
            "msg" => '操作成功',
            "code" => 0,
            "data" => $list,
            "count" => $count,
        );

    }

    public function replaceStr($name)
    {
        // 计算字符串长度，无论汉字还是英文字符全部为1
        $length = mb_strlen($name, 'utf-8');

        // 截取前面字符串
        $firstStr1 = mb_substr($name, 0, intval(ceil($length / 4)), 'utf-8');
        // 截取中间字符串代码
        $firstStr = mb_substr($name, intval(ceil($length / 4)), intval(floor($length / 2)), 'utf-8');
        // 截取剩余字符串
        $firstStr2 = mb_substr($name, intval(ceil($length / 4)) + intval(floor($length / 2)), intval(floor(($length + 1) / 2 - 1)), 'utf-8');

        return $firstStr1 . str_repeat("*", mb_strlen($firstStr, 'utf-8')) . $firstStr2;
    }


    /**
     * @Notes:获取用户与邮箱管理配置
     * @Interface getUserAccountConfig
     * @author: wuyu
     * @Time: 2023/6/2   17:54
     */
    public function getUserEmailConfig()
    {
        $config = [];
        //获取用户信息
        $config['user_list'] = RedisService::getUserList();

        return message("获取成功", true, $config);
    }


    /**
     * @Notes:添加或编辑
     * @Interface edit
     * @return array|void
     * @author: wuyu
     * @Time: 2023/6/3   16:45
     */
    public function edit()
    {
        try {
            $params = request()->all();
            $id = $params['id'] ?? 0;
            $email = $params['email_name'] ?? '';
            $password = $params['email_pass'] ?? '';
            $status = $params['status'] ?? 1;
            $userId = $params['user_id'] ?? 0;

            if (empty($email)) throw new \Exception('邮箱不能为空');
//            if (empty($password)) throw new \Exception('密码不能为空');
            if (empty($status)) throw new \Exception('状态不能为空');
            if (empty($userId)) throw new \Exception('用户不能为空');

            $data = [
                'email_name' => $email,
                'user_id' => $userId,
//                'email_pass' => $password
            ];
            $exists = $this->model->getOne([
//                ['email_name', '=', $email],
                ['user_id', '=', $userId],
            ]);
            if (!empty($exists) && empty($id)) {
                throw new \Exception('用户已存在,请勿重复添加');
            } elseif (!empty($exists) && $exists['id'] != $id) {
                throw new \Exception('用户已存在,请勿重复添加');
            }
            $UserModel = new UserModel();
            $userData = $UserModel->getOne([
                ['id', '=', $userId]
            ], 'id,username');
            $data['user_name'] = $userData['username'];
            if (empty($id)) {
                $data['create_user'] = $this->model->userId;
                $data['update_time'] = time();
                $data['create_time'] = time();
                $insertId = $this->model->insertGetId($data);
            } else {
                $data['update_user'] = $this->model->userId;
                $data['update_time'] = time();
                $insertId = $this->model->where('id', '=', $id)->update($data);
                $this->model->cacheReset($id, $data, $id);
            }
            if (empty($insertId)) throw new \Exception('操作失败');

            return message("保存成功", true, []);

        } catch (\Exception $e) {
            return message("保存失败:" . $e->getMessage(), false, []);
        }
    }

    public function status()
    {

        $params = request()->all();

        $id = $params['id'] ?? 0;
        $status = $params['status'] ?? 0;
        if (empty($id) || empty($status)) {
            return message("参数不存在", false, []);
        }
        $data = ['status' => $status];
        $this->model->where('id', $id)->update($data);
        $this->model->cacheReset($id, $data, $id);
        return message("操作成功", true, []);
    }


}
